/**
 * Created by sunny.w <iwisunny@gmail.com> on 15-4-25.
 */
wxi.namespace('wxi.ui', {
    //add modal box, based on bootstrap modal js component
    modal: function(opt){
        var opt = wxi.isObject(opt) ? opt :  {title: '', msg: '', cb:''},
            title = opt.title || 'modal title';
        var target;

        if(opt.target !== undefined){
            //target should has .wx-modal class
            target = $('.wx-modal').filter(function(i){
                return $(this).data('target') == 'md-'+opt.target;
            });
        }
        else{
            //the only modal instance
            target = $('#wx-modal');
        }

        //save target in global
        wxi.modal = target;

        var md = target,
            md_title = md.find('.modal-title'),
            md_body = md.find('.modal-body'),
            md_foot = md.find('.modal-footer');

        md_body.css('height', opt.height ? opt.height : '120px');
        md_body.parent('.modal-content').css('width', opt.width ? opt.width : '100%');
        md.css('left', opt.left ? opt.left : 0);

        md_title.text(title);

        do{
            if(opt.msg === false){
                break;
            }
            else if(typeof opt.msg == 'function'){
                md_body.html(opt.msg.call(null));
            }
            else {
                md_body.html(opt.msg);
            }
        }while(0);

        md_foot.find('.btn-primary').unbind('click');

        target.modal({
            keyboard: false,
            backdrop: false //点击遮罩不会退出
        }).show();

        if(opt.cb && typeof opt.cb =='function'){
            md_foot.find('.btn-primary').bind('click', function(){
                opt.cb( $(this), $(this).parents('#wx-modal') );
            });
        }

        //is shown event
        if(opt.is_shown && typeof opt.is_shown == 'function'){
            target.off('shown.bs.modal');
            target.on('shown.bs.modal', function(){
                opt.is_shown( target );
            });
        }
    },

    hideModal: function(cb){
        $('#wx-modal').add('.wx-modal').hide();
    }

});